<?php
/**
 * Created by PhpStorm.
 * User: luckystar_D
 * Date: 2017/1/21
 * Time: 上午11:44
 */

namespace api\modules\v1\models;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use izyue\admin\models\Member;
use izyue\admin\models\MemberSearch;
use izyue\admin\models\FlowPassGroup;
use izyue\admin\models\FlowPassGroupSearch;
use izyue\admin\models\DataOrder;
use izyue\admin\models\DataOrderSearch;
use izyue\admin\models\FlowPass;
use izyue\admin\models\FlowPassSearch;
use izyue\admin\models\FlowPacket;
use izyue\admin\models\FlowPacketSearch;
use izyue\admin\models\FlowValNo;
use izyue\admin\models\FlowValNoSearch;
use izyue\admin\models\Api;
use izyue\admin\models\ApiSearch;
use izyue\admin\models\BlanceLog;
use izyue\admin\models\BlanceLogSearch;
use api\modules\changyue;
use izyue\admin\models\Area;
use yii\log\Logger;
use linslin\yii2\curl\Curl;


class Site
{
    public static $app_id = 'Gl3FPNKc3r';
    public static $app_secret = 'IHOljUKaHopWmqDpHlai';
    //获取apikey对应用户信息
    public static function GetMemberInfoByApikey($apikey) {
        $res = array();
        $res = Member::find()->where(['apikey' => $apikey])->one();
        return $res;
    }

    //通道筛选
    public static function ConfirmApi($param) {
        $keywords = array();
        $return = self::GetApi($param);
        $apiinfo = Api::findOne($return['apiid']);
        $passinfo = self::GetFlowPassById($return['passid']);
        if (empty($apiinfo) || empty($passinfo)) {
            self::end(-8);
        }
        $keywords['keywords'] =  $apiinfo['keywords'];
        $keywords['apiid'] =  $return['apiid'];
        return $keywords;
    }
    //获取所有API
    public static function GetApis() {
        $apis = Api::find()->all();
        return $apis;
    }
    //获取通道所属API
    public static function GetApi($param) {
        $packet = self::ComparePacket($param);
        if (empty($packet)) {
            self::end(-8);
        }
        $apiid = 0;
        $passid = 0;
        $packetid = 0;
        $profit = array();
        //筛选最便宜通道
        foreach ($packet as $key => $value) {  //遍历同一接口下所有通道  $key : apiid;  $k : passid;
            foreach ($value as $k => $val) {   //遍历通道下所有流量包
                foreach ($val as $v) {
                    $profit[$key][$k][$v['id']] = $v['sale_price'] - $v['cost_price'] ;
                }
            }
        }
        foreach ($profit as $key => $value) {  //遍历同一接口下所有通道  $key : apiid;  $k : passid;
            foreach ($value as $k => $val) {   //遍历通道下所有流量包
                foreach ($val as $v) {
                    $packetid =  array_search(max($profit[$key][$k]),$profit[$key][$k]);
                    $passid =  array_search(max($profit[$key]),$profit[$key]);
                    $apiid =  array_search(max($profit),$profit);
                }
            }
        }
        $return = array (
            'packetid' => $packetid,
            'passid' => $passid,
            'apiid' => $apiid,
        );
        return $return;
    }
    //获取流量包
    public static function ComparePacket($param) {
        $packet = array();
        $packet_list = self::GetFlowPacket($param);
        if (empty($packet_list)) {
            self::end(-8);
        }
        foreach ($packet_list as $key => $value) {  //遍历同一接口下所有通道  $key : apiid;  $k : passid;
            foreach ($value as $k => $val) {   //遍历通道下所有流量包
                foreach ($val as $v) {
                    if ($v['num'] == $param['flow_val']) {
                        $packet[$key][$k][] = $v;  //与提交订单的流量想对应的流量包
                    }
                }
            }
        }
        return $packet;
    }
    //获取通道下流量包信息
    public static function GetFlowPacket($param) {
        $packet_info = array();
        $pass_array = self::GetPass($param);
        if (empty($pass_array)) {
            self::end(-8);
        }
        foreach ($pass_array as $value) {
            $packet_array[$value['apiid']][$value['id']] = explode(',', $value['type_ids']);
        }
        foreach ($packet_array as $key => $value) {
            foreach ($value as $k => $val) {
                foreach ($val as $v) {
                    $packet_info[$key][$k][] = self::GetFlowPacketById($v);
                }
            }
        }
        return $packet_info;
    }
    //获取流量通道
    public static function GetPass($param) {
        $pass_return = array();
        $member = self::GetMemberInfoByApikey($param['apikey']);
        $pass_group = self::GetFlowPassGroupByGroupId($member['pass_group']);
        //根据运营商筛选
        switch ($param['catName'])
        {
            case "中国移动" :
                $pass_array = explode(',', $pass_group['cmcc_pass']);
                break;
            case "中国联通" :
                $pass_array = explode(',', $pass_group['cucc_pass']);
                break;
            case "中国电信" :
                $pass_array = explode(',', $pass_group['ctcc_pass']);
                break;
            default :
                $pass_array = explode(',', $pass_group['all_pass']);
                break;
        }
        //根据省份地区筛选
        foreach ($pass_array as $value) {
            $pass = self::GetFlowPassById($value);
            //通道类型（省内/国内）筛选
            if ($param['scope'] == '0') {//国内
                $param['scope'] = 2;
            }
            if ($pass['in_where'] == $param['scope']) {
                if ($pass['area'] == 1) {//省份
                    $province = explode(',', $pass['province']);
                    foreach ($province as $val) {
                        $area = Area::findOne($val);
                        if ($area['name'] == $param['province']) {
                            $pass_return[] =  self::GetFlowPassById($value);
                        }
                    }
                } else {//全国
                    $pass_return[] =  self::GetFlowPassById($value);
                }
            }
        }
        return $pass_return;

    }
    //获取流量组
    public static function GetFlowPassGroupByGroupId($id) {
        $pass_group = array();
        $pass_group = FlowPassGroup::findOne($id);
        return $pass_group;
    }
    //获取流量通道
    public static function GetFlowPassById($id) {
        $pass = FlowPass::findOne($id);
        return $pass;
    }
    //获取流量包
    public static function GetFlowPacketById($id) {
        $pass = FlowPacket::findOne($id);
        return $pass;
    }
    public static function SaveOrder($param) {
        $res = self::GetMemberInfoByApikey($param['apikey']);
        switch ($param['catName'])
        {
            case "中国移动" :
                $operators = 1;
                break;
            case "中国联通" :
                $operators = 2;
                break;
            case "中国电信" :
                $operators = 3;
                break;
            default :
                $operators = 0;
                break;
        }
        $model = new DataOrder();
        $model->mid = $res['id'];
        $model->ordersn = self::BuildOrderNo();
        $model->type = 1;
        $model->status = 1;
        $model->phone_no = $param['phone_no'];
        $model->flow_val = $param['flow_val'];
        $model->operators = $operators;
        $model->out_order_id = $param['out_order_id'];
        $model->report_time = time();
        $model->desc = '';
        $model->apiid = $param['apiid'];
        $model->up_order_id = '';
        $model->createtime = time();
        if (!$model->save()) {
            Yii::getLogger()->log($model->errors, Logger::LEVEL_ERROR);
            self::end(-7);
        }
        self::UpdateBlance($param);
    }
    public static function BuildOrderNo() {
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    public static function UpdateBlance($param,$type = 0) {
        $member = self::GetMemberInfoByApikey($param['apikey']);
        $api = self::GetApi($param);
        $packet = self::GetFlowPacketById($api['packetid']);
        $pass = self::GetFlowPassById($api['passid']);
        $group = self::GetFlowPassGroupByGroupId($member['pass_group']);
        $discount_array = unserialize($group['discount']);
        if (!empty($api['passid']) && !empty($api['packetid']) && !empty($api['discount'])) {
            $discount =  $discount_array[$api['passid']][$api['packetid']]['discount'];
        } else {
            $discount = '';
        }
        if (!empty($discount)) {
            $discount_money = ($packet['sale_price'] * $discount)/100;
        } else {
            $discount_money = $packet['sale_price'];
        }
        if (empty($discount_money)) {
            self::end(-7);
        }
        $blance = new BlanceLog();
        if ($type == 1) {
            $money = $member['balance'] + $discount_money ;
            $blance->type = '退款';
        } else {
            if ($member['balance'] < $discount_money) {
                self::end(-6);
            }
            $money = $member['balance'] - $discount_money ;
            $blance->type = '消费';
        }
        Member::updateAll(
            array('balance'=>$money),
            'apikey=:apikey',
            array(':apikey'=>$param['apikey'])
        );
        $blance->mid = $member['id'];
        $blance->ordersn = $param['out_order_id'];
        $blance->money = $discount_money;
        $blance->createtime = time();
        if (!$blance->save()) {
            Yii::getLogger()->log($blance->errors, Logger::LEVEL_ERROR);
            self::end(-7);
        }
    }
    //获取对应订单信息
    public static function GetOrderInfoByOutOrderId($out_order_id) {
        if (empty($out_order_id)) {
            self::end(-1);
        } else {
            $res = DataOrder::find()->where(['out_order_id' => $out_order_id])->one();
            if (empty($res)) {
                self::end(-1);
            }
        }
        return $res;
    }
    //更新订单充值状态
    public static function UpdateOrderStatus($param) {
        $res = self::GetOrderInfoByOutOrderId($param['out_order_id']);
        DataOrder::updateAll(
            array('status'=>$param['status']),
            'out_order_id=:out_order_id',
            array(':out_order_id'=>$res['out_order_id'])
        );
    }
    public static function UpdateOrderNo($param) {
        $res = self::GetOrderInfoByOutOrderId($param['out_order_id']);
        DataOrder::updateAll(
            array('up_order_id'=>$param['order_id']),
            'out_order_id=:out_order_id',
            array(':out_order_id'=>$res['out_order_id'])
        );
    }
    //获取用户的回调地址
    public static function GetFlowValNo($param){
        $goodsid = FlowValNo::find()->where([
            'operator' => $param['operator'],
            'province' => $param['province'],
            'val' => $param['flow_val'],
            'isprovince' => $param['scope']
        ])->one();
        return $goodsid;

    }
    //获取用户的回调地址
    public static function GetBackUrl($mid){
        $info = Member::findOne($mid);
        return $info['back_url'];

    }
    public static function GetAllOrdersInHours() {
        $time = time()-(86400*7);
        $orders = DataOrder::find()->where([
            'and',
            ['status' => [1, 2]],
            ['>=' , 'createtime', $time]
        ])->all();
        return $orders;
    }
    public static function GetAllOrdersIsBack() {
        $time = time()-86400;
        $orders = DataOrder::find()->where([
            'and',
            ['status' => [3, 4]],
            ['>=' , 'createtime', $time]
        ])->all();
        return $orders;
    }
    public static function GetApiKeywordsByOutOrderId($out_order_id) {
        $res = self::GetOrderInfoByOutOrderId($out_order_id);
        $apiinfo = Api::findOne($res['apiid']);
        $apikeyword = $apiinfo['keywords'];
        return  $apikeyword;


    }
    //curl_http
    public static function curl_http($url,$param){
        $curl = new Curl();
        $response = $curl->setOption(
            CURLOPT_POSTFIELDS,
            http_build_query($param)
        )->post($url);
        return $response;
    }
    public static function end($code = 0, $data = array())
    {
        switch ($code)
        {
            case 0 :
                $message = '处理成功';
                break;
            case -1 :
                $message = '参数错误';
                break;
            case -2 :
                $message = '手机号码无法识别';
                break;
            case -3 :
                $message = '鉴权错误';
                break;
            case -5 :
                $message = '网络异常';
                break;
            case -6 :
                $message = '平台账户余额不足';
                break;
            case -7 :
                $message = '系统异常';
                break;
            case -8 :
                $message = '通道异常';
                break;
            default :
                $message = '提交成功';
                break;
        }
        echo json_encode([
            'code' => $code,
            'message' => $message,
            'data' => $data
        ], JSON_UNESCAPED_UNICODE);
        Yii::$app->end();
    }

}